'use strict';

const RouterService = require('../base');
const dayjs = require('dayjs');
const { Op } = require('sequelize');

class DailyMenuService extends RouterService {
  static get modelName() {
    return 'Business.DailyMenu';
  }

  // 重写列表查询的关联
  getListInclude() {
    return [
      {
        model: this.ctx.model.Business.Supplier,
        as: 'supplier',
        attributes: ['id', 'name']
      },
      {
        model: this.ctx.model.Business.Purchaser,
        as: 'purchaser',
        attributes: ['id', 'name']
      },
      {
        model: this.ctx.model.Business.MonthlyBidding,
        as: 'monthlyBidding',
        attributes: ['id', 'title', 'month']
      }
    ];
  }

  getPageInclude(){
    return this.getListInclude()
  }
  getDetailInclude() {
    return this.getListInclude()
  }
  async beforeUpdate(id, data) {
    if (data.status === 1) {
      // 查询是否存在菜单
      const menuItems = await this.ctx.model.Business.DailyMenuItem.findAll({
        where: {
          daily_menu_id: id,
          deleted: 0
        }
      })
      if (menuItems.length === 0) {
        throw new Error('未选择菜品，不能发布')
      }
    }
    return true
  }
  // 获取供应商的菜单列表
  async getSupplierMenus(supplierId) {
    return this.model.findAll({
      where: {
        supplier_id: supplierId,
        deleted: 0
      },
      order: [['menu_date', 'DESC']],
      include: this.getListInclude()
    });
  }

  // 获取采购员的菜单列表
  async getPurchaserMenus(purchaserId) {
    return this.model.findAll({
      where: {
        purchaser_id: purchaserId,
        deleted: 0
      },
      order: [['menu_date', 'DESC']],
      include: this.getListInclude()
    });
  }

  // 重写列表查询，支持按供应商ID过滤
  async list(query = {}, order = [['create_time', 'DESC']]) {
    const { supplierId, purchaserId } = query;

    if (supplierId) {
      query.supplier_id = supplierId;
    }

    if (purchaserId) {
      query.purchaser_id = purchaserId;
    }

    const result = await super.list(query, order);

    // 处理关联数据，添加显示字段
    if (result && result.length > 0) {
      result.forEach(item => {
        if (item.supplier) {
          item.supplier_name = item.supplier.name;
        }
        if (item.purchaser) {
          item.purchaser_name = item.purchaser.name;
        }
        if (item.monthlyBidding) {
          item.monthly_bidding_title = item.monthlyBidding.title;
        }
      });
    }

    return result;
  }

  // 重写创建方法，自动设置monthly_bidding_id
  async create(payload) {
    // 根据当前时间获取月份，查询对应的月度比价项目
    const currentMonth = this.getCurrentMonth(payload.menu_date);
    const monthlyBidding = await this.getMonthlyBiddingByMonth(currentMonth);

    if (!monthlyBidding) {
      throw new Error(`未找到${currentMonth}未进行比价，请先创建月度比价`);
    }
    if (monthlyBidding.status !== 3) {
      throw new Error(`${currentMonth}还未确定供应商，请先确定供应商`);
    }

    // 设置monthly_bidding_id
    payload.monthly_bidding_id = monthlyBidding.id;

    return super.create(payload);
  }

  // 获取当前月份 YYYY-MM 格式
  getCurrentMonth(date) {
    return dayjs(date).format('YYYY-MM');
  }

  // 根据月份获取月度比价项目
  async getMonthlyBiddingByMonth(month) {
    const { ctx } = this;
    const MonthlyBidding = ctx.model.Business.MonthlyBidding;

    return MonthlyBidding.findOne({
      where: {
        month,
        deleted: 0
      },
      order: [['create_time', 'DESC']]
    });
  }

   /**
   * Soft delete record
   * @param {String|Number} id
   * @param {String|Number} userId
   */
   async delete(id) {
    const model = await this.findById(id);
    if (!model) {
      throw new Error('删除对象不存在')
    }
    // 创建事务，删除菜单明细
    const transaction = await this.ctx.model.transaction();
    try {
      await this.ctx.model.Business.DailyMenuItem.destroy({
        where: {
          daily_menu_id: id
        },
        transaction
      })
      await this.model.destroy({
        where: {
          id
        },
        transaction
      })
      await transaction.commit();
      return true;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  // 获取采购统计数据
  async getPurchaseStatistics() {
    const { ctx } = this;
    // 获取今日日期
    const today = dayjs().format('YYYY-MM-DD');
    // 获取本月开始和结束日期
    const monthStart = dayjs().startOf('month').format('YYYY-MM-DD');
    const monthEnd = dayjs().endOf('month').format('YYYY-MM-DD');
    console.log('today',today)
    // 上一天
    const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    // 下一天
    const tomorrow = dayjs().add(1, 'day').format('YYYY-MM-DD');
    console.log(today, tomorrow)
    try {
      // 当日统计数据
      const todayStats = await ctx.model.Business.DailyMenuItem.findAll({
        include: [
          {
            model: ctx.model.Business.DailyMenu,
            as: 'dailyMenu',
            where: {
              menu_date: {
                [Op.between]: [today, tomorrow]
              },
              deleted: 0
            },
            attributes: []
          }
        ],
        attributes: [
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('base_price')), 'total_base_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('supplier_quoted_price')), 'total_supplier_quoted_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('actual_price')), 'total_actual_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('base_price * COALESCE(actual_quantity2, 0)')), 'total_base_amount'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('supplier_quoted_price * COALESCE(actual_quantity2, 0)')), 'total_supplier_quoted_amount'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('actual_price * COALESCE(actual_quantity2, 0)')), 'total_actual_amount']
        ],
        where: {
          deleted: 0
        },
        raw: true
      });
      console.log('todayStats',todayStats)
      // 本月统计数据
      const monthStats = await ctx.model.Business.DailyMenuItem.findAll({
        include: [
          {
            model: ctx.model.Business.DailyMenu,
            as: 'dailyMenu',
            where: {
              menu_date: {
                [Op.between]: [monthStart, monthEnd]
              },
              deleted: 0
            },
            attributes: []
          }
        ],
        attributes: [
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('base_price')), 'total_base_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('supplier_quoted_price')), 'total_supplier_quoted_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.col('actual_price')), 'total_actual_price'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('base_price * COALESCE(actual_quantity2, 0)')), 'total_base_amount'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('supplier_quoted_price * COALESCE(actual_quantity2, 0)')), 'total_supplier_quoted_amount'],
          [ctx.model.Sequelize.fn('SUM', ctx.model.Sequelize.literal('actual_price * COALESCE(actual_quantity2, 0)')), 'total_actual_amount']
        ],
        where: {
          deleted: 0
        },
        raw: true
      });

      // 格式化数据
      const formatAmount = (amount) => {
        return amount ? parseFloat(amount).toFixed(2) : '0.00';
      };

      const todayData = todayStats[0] || {};
      const monthData = monthStats[0] || {};

      return {
        today: {
          total_base_price: formatAmount(todayData.total_base_price),
          total_supplier_quoted_price: formatAmount(todayData.total_supplier_quoted_price),
          total_actual_price: formatAmount(todayData.total_actual_price),
          total_base_amount: formatAmount(todayData.total_base_amount),
          total_supplier_quoted_amount: formatAmount(todayData.total_supplier_quoted_amount),
          total_actual_amount: formatAmount(todayData.total_actual_amount)
        },
        month: {
          total_base_price: formatAmount(monthData.total_base_price),
          total_supplier_quoted_price: formatAmount(monthData.total_supplier_quoted_price),
          total_actual_price: formatAmount(monthData.total_actual_price),
          total_base_amount: formatAmount(monthData.total_base_amount),
          total_supplier_quoted_amount: formatAmount(monthData.total_supplier_quoted_amount),
          total_actual_amount: formatAmount(monthData.total_actual_amount)
        }
      };
    } catch (error) {
      console.error('获取采购统计数据失败:', error);
      // 返回默认的空数据
      return {
        today: {
          total_base_price: '0.00',
          total_supplier_quoted_price: '0.00',
          total_actual_price: '0.00',
          total_base_amount: '0.00',
          total_supplier_quoted_amount: '0.00',
          total_actual_amount: '0.00'
        },
        month: {
          total_base_price: '0.00',
          total_supplier_quoted_price: '0.00',
          total_actual_price: '0.00',
          total_base_amount: '0.00',
          total_supplier_quoted_amount: '0.00',
          total_actual_amount: '0.00'
        }
      };
    }
  }

  async delete(id) {
    const model = await this.findById(id);
    if (!model) {
      throw new Error('删除对象不存在')
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    // 删除菜单明细、菜单
    try {
      await this.ctx.model.Business.DailyMenuItem.destroy({
        where: {
          daily_menu_id: id
        },
        transaction
      })
      await this.model.destroy({
        where: {
          id
        },
        transaction
      })
      await transaction.commit();
      return true;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

module.exports = DailyMenuService;
